<!-- 公司信息 -->
<template>
  <!-- 顶部按钮 -->
  <div class="crud buttons">
    <el-button
      type="primary"
      modal
      @click=";(type = 'create'), (dialogVisible = true)"
      ><el-icon> <CirclePlusFilled /> </el-icon>新增
    </el-button>
    <el-button type="danger" @click="handleDletePeopleAll"
      ><el-icon> <DeleteFilled /> </el-icon>删除所选</el-button
    >
    <el-button type="primary" @click="exportFile"
      ><el-icon> <FolderOpened /> </el-icon>导出Elcel</el-button
    >
    <el-button type="primary" @click="handleprint"
      ><el-icon> <Printer /> </el-icon>打印</el-button
    >
  </div>
  <div class="project">
    <div class="top_box">
      <!-- 搜索框 -->
      <div class="search_box">
        <span class="searc_title">公司名称</span>
        <el-input v-model="input1" class="w_150" clearable />
        <span class="searc_title">联系人</span>
        <el-input v-model="input2" class="w_150" clearable />
        <span class="searc_title">电话</span>
        <el-input v-model="input3" class="w_150" clearable />
        <el-button
          type="primary"
          @click="handlinquire"
          @keydown.enter="keydown()"
          >查询</el-button
        >
      </div>
    </div>
    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="编辑信息"
      width="30%"
      :before-close="handleClose"
    >
      <el-form :model="form" label-width="160px" ref="formRef" :rules="rules">
        <el-form-item label="公司名称" prop="supplierName">
          <el-input v-model="form.supplierName" />
        </el-form-item>
        <el-form-item label="联系人" prop="supplierContacts">
          <el-input v-model="form.supplierContacts" />
        </el-form-item>
        <el-form-item label="电话" prop="supplierPhone">
          <el-input v-model="form.supplierPhone" />
        </el-form-item>
        <el-form-item label="传真">
          <el-input v-model="form.fax" />
        </el-form-item>
        <el-form-item label="邮箱" prop="supplierMail">
          <el-input v-model="form.supplierMail" />
        </el-form-item>
        <el-form-item label="公司地址">
          <el-input v-model="form.supplierAddress" />
        </el-form-item>
        <el-form-item label="公司介绍">
          <el-input v-model="form.supplierIntroduce" />
        </el-form-item>
        <el-form-item label="票据信息">
          <el-input v-model="form.supplierInvoice" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button
            v-if="type === 'create'"
            type="primary"
            @click="submitAndExit"
          >
            新增并退出
          </el-button>
          <el-button
            v-else-if="type === 'update'"
            type="primary"
            @click="setAndExit"
          >
            修改并退出
          </el-button>
          <!-- <el-button v-else type="primary" @click="dialogVisible = false">
            退出
          </el-button> -->
        </span>
      </template>
    </el-dialog>

    <!-- 表格渲染 -->
    <div class="main">
      <el-table ref="multipleTableRef" :data="userList" style="width: 100%">
        <el-table-column type="selection" ref="checked" align="center" />
        <el-table-column
          property="supplierName"
          label="公司名称"
          align="center"
        />
        <el-table-column
          property="supplierContacts"
          label="联系人"
          align="center"
        />
        <el-table-column property="supplierPhone" label="电话" align="center" />
        <el-table-column property="fax" label="传真" align="center" />
        <el-table-column property="supplierMail" label="邮箱" align="center" />
        <el-table-column
          property="supplierAddress"
          label="地址"
          align="center"
        />
        <el-table-column
          property="supplierIntroduce"
          label="公司简介"
          align="center"
        />
        <el-table-column
          property="supplierInvoice"
          label="票据信息"
          align="center"
        />

        <!-- 左侧操作按钮 -->
        <el-table-column fixed="left" label="操作" align="center" width="210">
          <template #default="scope">
            <el-button
              size="small"
              type="danger"
              @click="handleDletePeople(scope.row)"
              >删除</el-button
            >
            <el-button
              size="small"
              type="primary"
              @click="setOpendialogVisible(scope.row)"
              >修改</el-button
            >
            <el-button size="small" type="primary" @click="oncheck(scope.row)"
              >查看</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>

  <!-- 查看弹出框 -->
  <el-dialog
    v-model="dialogTableVisible"
    align-center
    title="详细信息"
    width="90%"
  >
    <el-table :data="form">
      <el-table-column
        property="supplierName"
        label="公司名称"
        width="150"
        align="center"
      />
      <el-table-column
        property="supplierContacts"
        label="联系人"
        width="150"
        align="center"
      />
      <el-table-column
        property="supplierPhone"
        label="电话"
        width="150"
        align="center"
      />
      <el-table-column property="fax" label="传真" width="150" align="center" />
      <el-table-column
        property="supplierMail"
        label="邮箱"
        width="150"
        align="center"
      />
      <el-table-column property="supplierAddress" label="地址" align="center" />
      <el-table-column
        property="supplierIntroduce"
        label="公司简介"
        width="150"
        align="center"
      />
      <el-table-column
        property="supplierInvoice"
        label="票据信息"
        width="150"
        align="center"
      />
    </el-table>
  </el-dialog>
</template>

<script setup lang="ts">
// 外部引入
import {
  getMaterialInfo,
  addMaterialInfo,
  deleteMaterialInfo,
  setMaterialInfo,
  dletematerialall,
} from '@/api/getapi'
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { utils, writeFileXLSX } from 'xlsx'

// 搜索框 点击搜索
const input1 = ref('')
const input2 = ref('')
const input3 = ref('')
const handlinquire = () => {
  let obj: any = {
    supplierName: input1.value,
    supplierContacts: input2.value,
    supplierPhone: input3.value,
  }
  // console.log(obj)
  // 排除空
  for (let key in obj) {
    if (obj[key] === '' || obj[key] === null) {
      delete obj[key]
    }
  }
  /*condition--搜索条件（obj）   data--被筛选的数据--arr  */
  let filter = (condition: any, data: any) => {
    return data.filter((item: any) => {
      return Object.keys(condition).every((key) => {
        return String(item[key]).includes(String(condition[key]).trim())
      })
    })
  }
  userList.value = filter(obj, allData.value)

  if (userList.value.length === 0) {
    ElMessage({
      type: 'error',
      message: '没有相关信息',
    })
  }
}
// 回车搜索

const keyDown: any = (e: { keyCode: number }) => {
  if (e.keyCode == 13 || e.keyCode == 108) {
    handlinquire()
  }
}

onMounted(() => {
  //绑定监听事件
  window.addEventListener('keydown', keyDown)
})

onUnmounted(() => {
  //销毁事件
  window.removeEventListener('keydown', keyDown, false)
})

// 增、改 按钮当前状态
const type = ref<string>('create')

// 表格引用
const multipleTableRef = ref<any>()
// 查看弹出框的状态
const dialogTableVisible = ref(false)

// 新增修改弹出跨国状态
let dialogVisible = ref(false)
// 新增修改表单关闭提示
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('确认关闭吗？关闭后无法保存信息！')
    .then(() => {
      done()
      form.value = {}
    })
    .catch(() => {
      // catch error
    })
}

// 搜索框筛选渲染数据
const allData = ref<any>()
// 列表渲染响应式数据
const userList: any = ref([])
// 数据 key:value
const form = ref<any>({
  projectName: '',
  userName: '',
  jobNumber: '',
  sex: '',
  age: '',
  nameID: '',
  job: '',
  phone: '',
  department: '',
  departmentLeader: '',
  accStatus: '',
  postscript: '',
})

// 获取列表数据

const getInfo = async () => {
  const result = await getMaterialInfo()
  console.log(result)
  userList.value = result
  allData.value = result
}
getInfo()
// 填写信息判断条件
const formRef = ref(null)
const rules = {
  supplierName: [{ required: true, message: '请填写公司名称!' }],
  supplierContacts: [{ required: true, message: '请填写公司联系人!' }],
  supplierPhone: [{ required: true, message: '请填写联系人电话!' }],
  supplierMail: [{ required: true, message: '请填写联系邮箱!' }],
}

// 新增并退出
const submitAndExit = async () => {
  // 验证填写信息是否符合要求
  const has = await formRef.value?.validate()
  console.log(has)
  if (has) {
    try {
      const forData = form.value
      console.log(forData)
      const result = await addMaterialInfo(forData)
      console.log('添加:', result)
      form.value = {}
      dialogVisible.value = false
      ElMessage({
        message: '添加成功',
        type: 'success',
        duration: 1500,
      })
    } catch (error) {
      ElMessage({
        message: '手机号重复，添加失败！',
        type: 'error',
        duration: 1500,
      })
    }
    getInfo()
  }
  // else {  if..else..判断不显示
  //   ElMessage({
  //     message: '请完整填写必填项 ^.^',
  //     type: 'error',
  //     duration: 1500,
  //   })
  // }
}

// 删除按钮
const handleDletePeople = async (prod: any) => {
  // console.log('删除：', prod)
  try {
    const result = await deleteMaterialInfo(prod)
    console.log(result)
    userList.value = result
    ElMessage({
      message: '删除成功',
      type: 'success',
      duration: 1500,
    })
  } catch (error) {
    console.log(error)
  }
}

//修改按钮
const setOpendialogVisible = (prod: any) => {
  type.value = 'update'
  console.log('修改的', prod)
  dialogVisible.value = true
  form.value = prod
}
// 修改并退出
const setAndExit = async () => {
  const result = await setMaterialInfo(form.value)
  console.log('后端返回的', result)
  //清空表单
  form.value = {}
  // 关闭表单
  dialogVisible.value = false
  // 返回修改后的数组赋值给表格
  userList.value = result
  ElMessage({
    message: '修改成功',
    type: 'success',
    duration: 1500,
  })
}

// 导出
function exportFile() {
  const data = multipleTableRef.value.getSelectionRows()
  // console.log('选中数据:', data)

  const ws = utils.json_to_sheet(data)
  const wb = utils.book_new()
  utils.book_append_sheet(wb, ws, '项目信息')
  writeFileXLSX(wb, '公司信息.xlsx')
}
// 多项删除or删除所选
const handleDletePeopleAll = async () => {
  try {
    const data = multipleTableRef.value.getSelectionRows()
    console.log('选中数据:', data) //数组
    const result = await dletematerialall(data)
    console.log(result)
    // 返回修改后的数组赋值给表格
    userList.value = result
    ElMessage({
      message: '删除成功',
      type: 'success',
      duration: 1500,
    })
  } catch (error) {
    console.log(error)
  }
}
// 打印按钮
const handleprint = () => {
  window.print()
}

// 查看按钮
const oncheck = (prod: any) => {
  // type.value = ''
  dialogTableVisible.value = true
  const arr = []
  arr.push(prod)
  form.value = arr
}
</script>

<style lang="scss" scoped>
.search_box {
  .searc_title {
    font-size: 16px;
    margin-left: 20px;
  }

  .w_150 {
    width: 150px;
    margin: 20px;
  }
}

.top_box {
  float: left;
  width: 100%;

  .breadcrumb {
    margin-left: 10px;
    margin-top: 20px;
  }

  .project {
    float: left;
    width: 100%;
  }
}
.crud {
  margin: 10px;
  float: right;
}
.main {
  margin: auto;
  width: 98%;
}
</style>
